package net.huadong.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * NIO 客户端消息处理现成
 */
public class TimeClientHandle implements Runnable {
    private String ip;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop = false;

    /**
     * 初始化，创建通道和多路复用器，设置为非阻塞模式
     *
     * @param ip
     * @param port
     */
    public TimeClientHandle(String ip, int port) {
        this.ip = ip;
        this.port = port;
        try {
            selector = Selector.open();//创建多路复用器
            socketChannel = SocketChannel.open();//创建通道
            socketChannel.configureBlocking(false);//设置非阻塞
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            this.doConnect();//建立连接
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()) {
                    key = it.next();
                    it.remove();
                    try {
                        handleInput(key);
                    } catch (IOException e) {
                        if (key != null) {
                            key.cancel();
                            if (key.channel() != null) {
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * key 消息处理
     *
     * @param key
     * @throws IOException
     */
    private void handleInput(SelectionKey key) throws IOException {

        //消息是否有效
        if (key.isValid()) {
            SocketChannel sc = (SocketChannel) key.channel();
            //如果doConnect方法未收到连接成功，这里处理connect状态
            if (key.isConnectable()) {
                if (sc.finishConnect()) {
                    //完成连接，修改通道状态为read传输数据
                    sc.register(selector, SelectionKey.OP_READ);
                    //传输数据
                    doWrite(sc);
                } else {
                    //否则连接失败
                    System.exit(1);
                }
            }
            //通道已经准备好读取
            if (key.isReadable()) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);//ByteBuffer解码
                int readBytes = sc.read(byteBuffer);
                if (readBytes > 0) {
                    byteBuffer.flip();
                    byte[] bytes = new byte[byteBuffer.remaining()];
                    byteBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("服务器返回结果：" + body);
                    key.cancel();
                    sc.close();
                    this.stop = true;
                } else if (readBytes < 0) {
                    key.cancel();
                    sc.close();
                } else {

                }
            }
        }
    }

    /**
     * 建立连接
     *
     * @throws IOException
     */
    private void doConnect() throws IOException {
        //异步连接，判断是否连接成功
        if (socketChannel.connect(new InetSocketAddress(ip, port))) {
            //连接成功，改变通道状态，设置为read，数据传输
            socketChannel.register(selector, SelectionKey.OP_READ);
            //传输数据
            doWrite(socketChannel);

        } else {
            //连接未返回成功，监听connect状态
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
    }

    /**
     * 发送数据
     *
     * @param sc
     * @throws IOException
     */
    private void doWrite(SocketChannel sc) throws IOException {
        byte[] req = "QUERY_TIME_ORDER".getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(req.length);
        byteBuffer.put(req);
        byteBuffer.flip();
        sc.write(byteBuffer);
        if (!byteBuffer.hasRemaining()) {
            System.out.println("向服务器发送指令成功");
        }
    }
}
